package com.songlei.rtcadriondh265demo.utils

import android.media.MediaCodecInfo
import android.media.MediaCodecList
import android.os.Build

object CodecUtils {
    data class CodecInfo(
        val name: String,
        val mimeType: String,
        val isEncoder: Boolean,
        val isHardwareAccelerated: Boolean
    )

    data class SupportedCodecs(
        val videoCodecs: List<CodecInfo>,
        val audioCodecs: List<CodecInfo>
    )

  private  fun getSupportedCodecs(): SupportedCodecs {
        val videoCodecs = mutableListOf<CodecInfo>()
        val audioCodecs = mutableListOf<CodecInfo>()

        val codecList = MediaCodecList(MediaCodecList.ALL_CODECS)
        codecList.codecInfos.forEach { codecInfo ->
            codecInfo.supportedTypes.forEach { mimeType ->
                val entry = CodecInfo(
                    name = codecInfo.name,
                    mimeType = mimeType,
                    isEncoder = codecInfo.isEncoder,
                    isHardwareAccelerated = isHardwareAccelerated(codecInfo)
                )

                when {
                    mimeType.startsWith("video/") -> videoCodecs.add(entry)
                    mimeType.startsWith("audio/") -> audioCodecs.add(entry)
                }
            }
        }

        return SupportedCodecs(videoCodecs, audioCodecs)
    }

    fun getFormattedCodecInfo(): String {
        val codecs = getSupportedCodecs()
        val sb = StringBuilder()

        sb.append("===== 视频编解码器 =====\n")
        codecs.videoCodecs.forEach { appendCodecInfo(sb, it) }

        sb.append("\n===== 音频编解码器 =====\n")
        codecs.audioCodecs.forEach { appendCodecInfo(sb, it) }

        return sb.toString()
    }

    private fun isHardwareAccelerated(codecInfo: MediaCodecInfo): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            codecInfo.isHardwareAccelerated
        } else {
            codecInfo.name.startsWith("OMX.") && !codecInfo.name.startsWith("OMX.google.")
        }
    }

    private fun appendCodecInfo(sb: StringBuilder, info: CodecInfo) {
        sb.append("${info.name.padEnd(35)} | ")
            .append("${info.mimeType.padEnd(12)} | ")
            .append(if (info.isEncoder) "编码器" else "解码器").append(" | ")
            .append(if (info.isHardwareAccelerated) "✅ 硬件" else "🖥️ 软件")
            .append("\n")
    }
}